package com.liupf.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.liupf.common.utils.Constants;
import com.liupf.common.utils.TimeUtil;
import com.liupf.common.utils.TypeConstant;
import com.liupf.domain.OperatorLog;

public class OperatorController extends Controller{

	private Log logger = LogFactory.getLog(this.getClass());
	
	public void index(){
		String company=(String) getSession().getAttribute("company");
		String userRole = (String) getSession().getAttribute(Constants.SESSION_USER_ROLE);
		String beginDateStr = this.getPara("beginDate");
		String endDateStr = this.getPara("endDate");
		if(beginDateStr == null 
				|| "".equals(beginDateStr)
				|| endDateStr == null
				|| "".equals(endDateStr)){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			setAttr("beginDate", sdf.format(Calendar.getInstance().getTime()));
			setAttr("endDate", sdf.format(Calendar.getInstance().getTime()));
			
			render("operator_index.ftl");
			return;
		}
		Date beginDate = TimeUtil.parse(beginDateStr, "yyyy-MM-dd", new Date());
		Date endDate = TimeUtil.parse(endDateStr, "yyyy-MM-dd", new Date());
		beginDate = setTime(beginDate, 0, 0, 0, 0);
		endDate = setTime(endDate, 23, 59, 59, 999);
		
		TypeConstant.OperatorType[] operatorTypeArray = TypeConstant.OperatorType.values();
		
		StringBuffer from  = new StringBuffer();
		from.append("from  operator_log o where 1=1 ");
		if(Constants.ROLE_BRAND_MANAGER.equals(userRole) || Constants.ROLE_MIDDLE_MANAGER.equals(userRole)){
			from.append(" and o.company='" + company + "'") ;
		}
		if(beginDateStr != null && endDateStr != null){
			from.append(" and o.create_time >= '"+ beginDateStr +" 00:00:00'");
			from.append(" and o.create_time < '"+ endDateStr +" 23:59:59'");
		}
		
		from.append(" order by id desc");
		Page<OperatorLog> page = OperatorLog.dao.paginate(getParaToInt(0, 1), 
														30,
														"select * ",
														from.toString());
		setAttr("page", page);
		setAttr("operatorTypeArray", operatorTypeArray);
		
		setAttr("beginDate", beginDateStr);
		setAttr("endDate", endDateStr);
		
		render("operator_index.ftl");
	}
	
	private Date setTime(Date date, int hour, int minute, int second, int ms) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.MINUTE, minute);
		calendar.set(Calendar.SECOND, second);
		calendar.set(Calendar.HOUR_OF_DAY, hour);
		calendar.set(Calendar.MILLISECOND, ms);
		date = calendar.getTime();
		return date;
	}
}
